<template>
  <div class="intelligent-qa">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
      <div class="container mx-auto px-6 py-4">
        <div class="flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-800">智能问答</h1>
          <div class="flex items-center space-x-4">
            <el-button @click="clearHistory">
              <i class="fas fa-trash-alt mr-2"></i>清空记录
            </el-button>
            <el-button @click="exportHistory">
              <i class="fas fa-download mr-2"></i>导出记录
            </el-button>
          </div>
        </div>
      </div>
    </header>

    <div class="qa-container">
      <div class="container mx-auto px-6 py-6">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <!-- 问答区域 -->
          <div class="lg:col-span-2">
            <div class="bg-white rounded-lg shadow-sm h-full flex flex-col">
              <!-- 聊天窗口 -->
              <div class="chat-window flex-1 p-6 overflow-y-auto" ref="chatWindow">
                <div v-if="chatHistory.length === 0" class="empty-state text-center py-12">
                  <div class="mb-4">
                    <i class="fas fa-robot text-6xl text-gray-300"></i>
                  </div>
                  <h3 class="text-lg font-medium text-gray-600 mb-2">欢迎使用法律智能问答</h3>
                  <p class="text-gray-500">请输入您的法律问题，我将为您提供专业解答</p>
                </div>
                
                <div v-else class="chat-messages space-y-4">
                  <div v-for="(message, index) in chatHistory" :key="index" 
                       :class="['message', message.type === 'user' ? 'user-message' : 'ai-message']">
                    <div v-if="message.type === 'user'" class="flex justify-end">
                      <div class="message-content bg-blue-600 text-white rounded-lg px-4 py-3 max-w-xs lg:max-w-md">
                        {{ message.content }}
                      </div>
                      <div class="avatar ml-3">
                        <div class="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center">
                          <i class="fas fa-user text-white text-sm"></i>
                        </div>
                      </div>
                    </div>
                    
                    <div v-else class="flex">
                      <div class="avatar mr-3">
                        <div class="w-8 h-8 bg-gray-600 rounded-full flex items-center justify-center">
                          <i class="fas fa-robot text-white text-sm"></i>
                        </div>
                      </div>
                      <div class="message-content bg-gray-100 rounded-lg px-4 py-3 max-w-xs lg:max-w-md">
                        <div v-if="message.isLoading" class="loading-dots">
                          <span></span>
                          <span></span>
                          <span></span>
                        </div>
                        <div v-else>
                          <div class="ai-response">
                            {{ message.content }}
                          </div>
                          <div v-if="message.references && message.references.length > 0" 
                               class="references mt-3 pt-3 border-t border-gray-200">
                            <p class="text-xs text-gray-500 mb-2">参考法条：</p>
                            <div class="space-y-1">
                              <div v-for="ref in message.references" :key="ref.id" 
                                   class="text-xs bg-blue-50 text-blue-700 px-2 py-1 rounded">
                                {{ ref.title }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 输入区域 -->
              <div class="input-area border-t border-gray-200 p-6">
                <div class="flex space-x-3">
                  <el-input
                    v-model="currentQuestion"
                    placeholder="请输入您的法律问题..."
                    class="flex-1"
                    @keyup.enter="askQuestion"
                    :disabled="isAsking"
                  >
                    <template #suffix>
                      <el-button 
                        text 
                        @click="askQuestion" 
                        :disabled="!currentQuestion.trim() || isAsking"
                        class="!border-none"
                      >
                        <i v-if="isAsking" class="fas fa-spinner fa-spin text-gray-400"></i>
                        <i v-else class="fas fa-paper-plane text-blue-600"></i>
                      </el-button>
                    </template>
                  </el-input>
                </div>
                
                <!-- 快捷问题 -->
                <div class="quick-questions mt-4">
                  <p class="text-sm text-gray-600 mb-2">快捷问题：</p>
                  <div class="flex flex-wrap gap-2">
                    <el-tag 
                      v-for="question in quickQuestions" 
                      :key="question"
                      @click="selectQuickQuestion(question)"
                      class="cursor-pointer hover:bg-blue-50"
                    >
                      {{ question }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 侧边栏 -->
          <div class="space-y-6">
            <!-- 专业领域 -->
            <div class="bg-white rounded-lg shadow-sm p-6">
              <h3 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fas fa-graduation-cap text-blue-600 mr-2"></i>
                专业领域
              </h3>
              <div class="space-y-2">
                <div v-for="area in expertiseAreas" :key="area.id" 
                     @click="selectArea(area)"
                     :class="['area-item p-3 rounded-lg cursor-pointer transition-colors',
                             selectedArea?.id === area.id ? 'bg-blue-50 border border-blue-200' : 'bg-gray-50 hover:bg-gray-100']">
                  <div class="flex items-center justify-between">
                    <span class="font-medium text-gray-800">{{ area.name }}</span>
                    <span class="text-xs text-gray-500">{{ area.cases }}件案例</span>
                  </div>
                  <p class="text-sm text-gray-600 mt-1">{{ area.description }}</p>
                </div>
              </div>
            </div>
            
            <!-- 热门问题 -->
            <div class="bg-white rounded-lg shadow-sm p-6">
              <h3 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fas fa-fire text-red-500 mr-2"></i>
                热门问题
              </h3>
              <div class="space-y-3">
                <div v-for="popular in popularQuestions" :key="popular.id" 
                     @click="selectPopularQuestion(popular.question)"
                     class="popular-question cursor-pointer p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                  <p class="text-sm font-medium text-gray-800">{{ popular.question }}</p>
                  <div class="flex items-center justify-between mt-2">
                    <span class="text-xs text-gray-500">{{ popular.category }}</span>
                    <span class="text-xs text-blue-600">{{ popular.views }}次查看</span>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 法律法规 -->
            <div class="bg-white rounded-lg shadow-sm p-6">
              <h3 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fas fa-book text-green-600 mr-2"></i>
                相关法规
              </h3>
              <div class="space-y-2">
                <div v-for="law in relevantLaws" :key="law.id" 
                     class="law-item p-3 bg-gray-50 rounded-lg">
                  <p class="text-sm font-medium text-gray-800">{{ law.title }}</p>
                  <p class="text-xs text-gray-600 mt-1">{{ law.article }}</p>
                  <div class="flex items-center justify-between mt-2">
                    <span class="text-xs text-gray-500">{{ law.date }}</span>
                    <el-button size="small" text @click="viewLaw(law)">查看</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'IntelligentQA',
  setup() {
    const chatWindow = ref(null)
    const currentQuestion = ref('')
    const isAsking = ref(false)
    const selectedArea = ref(null)
    
    const chatHistory = ref([])
    
    // 快捷问题
    const quickQuestions = ref([
      '交通事故责任如何认定？',
      '工伤赔偿标准是什么？',
      '合同违约如何处理？',
      '劳动仲裁流程怎样？'
    ])
    
    // 专业领域
    const expertiseAreas = ref([
      {
        id: 1,
        name: '交通事故',
        description: '交通事故责任认定、保险理赔',
        cases: 156
      },
      {
        id: 2,
        name: '劳动纠纷',
        description: '劳动合同、工伤赔偿',
        cases: 89
      },
      {
        id: 3,
        name: '合同纠纷',
        description: '合同违约、责任承担',
        cases: 134
      },
      {
        id: 4,
        name: '侵权责任',
        description: '人身损害、财产损失',
        cases: 76
      }
    ])
    
    // 热门问题
    const popularQuestions = ref([
      {
        id: 1,
        question: '交通事故对方全责，我的车损如何赔偿？',
        category: '交通事故',
        views: 1234
      },
      {
        id: 2,
        question: '公司无故辞退员工需要赔偿多少钱？',
        category: '劳动纠纷',
        views: 987
      },
      {
        id: 3,
        question: '购房合同违约金最高不能超过多少？',
        category: '合同纠纷',
        views: 765
      },
      {
        id: 4,
        question: '工伤认定需要哪些材料？',
        category: '工伤赔偿',
        views: 543
      }
    ])
    
    // 相关法规
    const relevantLaws = ref([
      {
        id: 1,
        title: '民法典',
        article: '第一千二百一十三条',
        date: '2021-01-01',
        content: '机动车发生交通事故造成损害的...'
      },
      {
        id: 2,
        title: '劳动法',
        article: '第四十七条',
        date: '1995-01-01',
        content: '经济补偿按劳动者在本单位工作的年限...'
      },
      {
        id: 3,
        title: '合同法',
        article: '第一百一十四条',
        date: '1999-10-01',
        content: '当事人可以约定一方违约时应当...'
      }
    ])
    
    // 选择专业领域
    const selectArea = (area) => {
      selectedArea.value = area
      ElMessage.success(`已切换到${area.name}领域`)
    }
    
    // 选择快捷问题
    const selectQuickQuestion = (question) => {
      currentQuestion.value = question
      askQuestion()
    }
    
    // 选择热门问题
    const selectPopularQuestion = (question) => {
      currentQuestion.value = question
      askQuestion()
    }
    
    // 提问
    const askQuestion = async () => {
      if (!currentQuestion.value.trim() || isAsking.value) return
      
      const question = currentQuestion.value.trim()
      currentQuestion.value = ''
      
      // 添加用户问题
      chatHistory.value.push({
        type: 'user',
        content: question,
        timestamp: new Date()
      })
      
      // 添加AI加载状态
      chatHistory.value.push({
        type: 'ai',
        content: '',
        isLoading: true,
        timestamp: new Date()
      })
      
      isAsking.value = true
      
      // 滚动到底部
      await nextTick()
      scrollToBottom()
      
      try {
        // 模拟AI回答延迟
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        // 生成AI回答
        const answer = generateAIAnswer(question)
        
        // 更新最后一条消息
        const lastMessage = chatHistory.value[chatHistory.value.length - 1]
        lastMessage.isLoading = false
        lastMessage.content = answer.content
        lastMessage.references = answer.references
        
      } catch (error) {
        ElMessage.error('问答服务暂时不可用，请稍后重试')
        // 移除加载中的消息
        chatHistory.value.pop()
      } finally {
        isAsking.value = false
        await nextTick()
        scrollToBottom()
      }
    }
    
    // 生成AI回答
    const generateAIAnswer = (question) => {
      const answers = {
        '交通事故': {
          content: '根据《道路交通安全法》和相关司法解释，交通事故责任认定主要依据当事人的行为对发生道路交通事故所起的作用以及过错的严重程度。一般分为全部责任、主要责任、同等责任、次要责任和无责任五种情况。具体认定需要交警部门根据现场勘查、证据收集等情况进行判断。',
          references: [
            { id: 1, title: '道路交通安全法第76条' },
            { id: 2, title: '交通事故处理程序规定' }
          ]
        },
        '工伤': {
          content: '工伤赔偿标准根据《工伤保险条例》规定，包括医疗费、住院伙食补助费、交通费、护理费、停工留薪期工资、一次性伤残补助金等。具体金额根据伤残等级、本人工资、统筹地区职工平均工资等因素计算。建议先进行工伤认定，再进行劳动能力鉴定，最后计算赔偿金额。',
          references: [
            { id: 1, title: '工伤保险条例第30条' },
            { id: 2, title: '工伤保险条例第37条' }
          ]
        },
        '合同': {
          content: '合同违约的处理方式主要包括：1）要求继续履行；2）采取补救措施；3）赔偿损失；4）支付违约金。根据《民法典》规定，违约金不得超过实际损失的30%。当事人可以协商解决，也可以通过诉讼途径解决。建议先保存好相关证据，再选择适当的救济方式。',
          references: [
            { id: 1, title: '民法典第577条' },
            { id: 2, title: '民法典第585条' }
          ]
        }
      }
      
      // 简单的关键词匹配
      for (const [key, value] of Object.entries(answers)) {
        if (question.includes(key)) {
          return value
        }
      }
      
      // 默认回答
      return {
        content: '感谢您的提问。这是一个很好的法律问题，建议您提供更多具体情况以便我给出更准确的建议。您也可以选择左侧的专业领域，我会为您提供该领域的专业解答。如需要详细的法律意见，建议咨询专业律师。',
        references: []
      }
    }
    
    // 滚动到底部
    const scrollToBottom = () => {
      if (chatWindow.value) {
        chatWindow.value.scrollTop = chatWindow.value.scrollHeight
      }
    }
    
    // 清空记录
    const clearHistory = () => {
      chatHistory.value = []
      ElMessage.success('聊天记录已清空')
    }
    
    // 导出记录
    const exportHistory = () => {
      if (chatHistory.value.length === 0) {
        ElMessage.warning('暂无聊天记录可导出')
        return
      }
      
      let exportText = '智能问答记录\n\n'
      chatHistory.value.forEach((message, index) => {
        if (!message.isLoading) {
          const type = message.type === 'user' ? '问' : '答'
          exportText += `${index + 1}. ${type}：${message.content}\n\n`
        }
      })
      
      const blob = new Blob([exportText], { type: 'text/plain' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `智能问答记录_${new Date().toLocaleDateString()}.txt`
      a.click()
      URL.revokeObjectURL(url)
      
      ElMessage.success('记录导出成功')
    }
    
    // 查看法规
    const viewLaw = (law) => {
      ElMessage.info(`查看${law.title} ${law.article}`)
    }
    
    onMounted(() => {
      // 初始化选择第一个专业领域
      selectedArea.value = expertiseAreas.value[0]
    })
    
    return {
      chatWindow,
      currentQuestion,
      isAsking,
      selectedArea,
      chatHistory,
      quickQuestions,
      expertiseAreas,
      popularQuestions,
      relevantLaws,
      selectArea,
      selectQuickQuestion,
      selectPopularQuestion,
      askQuestion,
      clearHistory,
      exportHistory,
      viewLaw
    }
  }
}
</script>

<style scoped>
.intelligent-qa {
  min-height: 100vh;
  background-color: #f9fafb;
}

.chat-window {
  max-height: 600px;
  min-height: 400px;
}

.message {
  margin-bottom: 16px;
}

.message-content {
  word-wrap: break-word;
  line-height: 1.5;
}

.loading-dots {
  display: flex;
  align-items: center;
  gap: 4px;
}

.loading-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #9ca3af;
  animation: loading 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.ai-response {
  white-space: pre-wrap;
}

.references {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e5e7eb;
}

.area-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.popular-question:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.law-item {
  transition: all 0.2s ease;
}

.law-item:hover {
  background-color: #f3f4f6;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .chat-window {
    max-height: 400px;
    min-height: 300px;
  }
}

@media (max-width: 768px) {
  .qa-container .container {
    padding: 16px;
  }
  
  .chat-window {
    max-height: 350px;
    min-height: 250px;
  }
  
  .message-content {
    max-width: 280px;
  }
}
</style>

